﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Data.SqlClient;
using System.Globalization;
using System.Windows.Shapes;

namespace 餐饮管理系统
{
    public partial class MainWindow : Window
    {
        private void loadMonthSelected()
        {
            financeListBox.Items.Clear();
            ListBoxItem dateListBoxItem = CaiwuListBox.SelectedItem as ListBoxItem;

            if (dateListBoxItem == null)
                return;

            string[] yearMonth = dateListBoxItem.Content.ToString().Trim().Split('-');

            int year = int.Parse(yearMonth[0]);
            int month = int.Parse(yearMonth[1]);

            string branchName = getBranchName();
            if (branchName == null)
            {
                return;
            }

            financeGraph(year, month);

            string sql = "select * from FinanceTable where month = " + month + " and year = " + year
                       + " and branch_name = '" + branchName + "'";
            SqlDataReader dataReader = databaseConnect.GetDataReader(sql);
            while (dataReader.Read())
            {
                ListBoxItem item = new ListBoxItem();
                item.SetResourceReference(ListBoxItem.StyleProperty, "FinanceRecordItem");
                item.ApplyTemplate();
                Label dateLbl = item.Template.FindName("date", item) as Label;
                Label itemLbl = item.Template.FindName("item", item) as Label;
                Label countLbl = item.Template.FindName("count", item) as Label;
                Label moneyLbl = item.Template.FindName("money", item) as Label;

                dateLbl.Content = dataReader[6].ToString().Trim() + "年 "
                    + dataReader[1].ToString().Trim() + "月 "
                    + dataReader[5].ToString().Trim() + "日 ";

                itemLbl.Content = dataReader[2].ToString().Trim();

                countLbl.Content = dataReader[3].ToString().Trim() + " × " + dataReader[4].ToString().Trim();
                moneyLbl.Content = ((int)dataReader[3] * (double)dataReader[4]).ToString();

                financeListBox.Items.Add(item);
            }
            dataReader.Close();
        }

        private void updateFinance()
        {
            //ListBoxItem dateListBoxItem = CaiwuListBox.SelectedItem as ListBoxItem;

            //if (dateListBoxItem == null)
            //    return;

            //string date = dateListBoxItem.Content.ToString().Trim();

            int month = GetMonth(DateTime.Now);
            int day = GetDay(DateTime.Now);
            int year = GetYear(DateTime.Now);

            double price = double.Parse(this.price.Text);
            int number = int.Parse(this.number.Text);
            string itemName = this.itemName.Text.Trim();



            ListBoxItem item = new ListBoxItem();
            item.SetResourceReference(ListBoxItem.StyleProperty, "FinanceRecordItem");
            item.ApplyTemplate();
            Label dateLbl = item.Template.FindName("date", item) as Label;
            Label itemLbl = item.Template.FindName("item", item) as Label;
            Label countLbl = item.Template.FindName("count", item) as Label;
            Label moneyLbl = item.Template.FindName("money", item) as Label;

            dateLbl.Content = year.ToString() + "年 "
                + month.ToString() + "月 "
                + day.ToString() + "日 ";

            itemLbl.Content = itemName.Trim();

            countLbl.Content = number.ToString() + " × " + price.ToString();
            moneyLbl.Content = (number * price).ToString();

            financeListBox.Items.Add(item);

            string branchName = getBranchName();
            if (branchName == null)
            {
                return;
            }
            string sql = "insert into FinanceTable values ("
                    + month + ",'"
                    + itemName + "',"
                    + number + ","
                    + price + ","
                    + day + ","
                    + year + ",'"
                    + branchName + "')";
            databaseConnect.ExecuteQuery(sql);

            this.price.Clear();
            this.number.Clear();
            this.itemName.Clear();


            ListBoxItem monthListBoxItem = new ListBoxItem();
            monthListBoxItem.SetResourceReference(ListBoxItem.StyleProperty, "ListBoxItemStyle1");
            monthListBoxItem.Content = year.ToString() + "-" + month.ToString();

            bool unique = true;
            foreach (ListBoxItem lbi in CaiwuListBox.Items)
            {
                if (lbi.Content.Equals(monthListBoxItem.Content))
                {
                    unique = false;
                }
            }
            if (unique)
            {
                CaiwuListBox.Items.Add(monthListBoxItem);
            }

            financeGraph(year, month);

        }

        private void initFinance()
        {
            CaiwuListBox.Items.Clear();
            financeListBox.Items.Clear();

            int month;
            int year;
            string branchName = getBranchName();

            //ListBoxItem item = new ListBoxItem();
            //item.SetResourceReference(ListBoxItem.StyleProperty, "FinanceListBoxItem");

            int maxYear;
            int maxMonth;
            if (branchName == null)
            {
                return;
            }
            string sqlYear = "select max(year) from FinanceTable where branch_name = '" + branchName + "'";
            SqlDataReader dataReaderYear = databaseConnect.GetDataReader(sqlYear);
            if (dataReaderYear.Read())
            {
                if (dataReaderYear[0].ToString() == "")
                {
                    dataReaderYear.Close();
                    return;
                }
                maxYear = (int)dataReaderYear[0];
                dataReaderYear.Close();

                string sqlMonth = "select max(month) from FinanceTable where year = " + maxYear
                                + " and branch_name = '" + branchName + "'";
                SqlDataReader dataReaderMonth = databaseConnect.GetDataReader(sqlMonth);
                if (dataReaderMonth.Read())
                {
                    maxMonth = (int)dataReaderMonth[0];
                    dataReaderMonth.Close();
                    year = maxYear - 1;
                    month = maxMonth;

                    financeGraph(maxYear, maxMonth);
                    string sqlYearMonth = "select * from FinanceTable where year = " + (maxYear).ToString()
                                        + " and month = " + (maxMonth).ToString()
                                        + " and branch_name = '" + branchName + "'";
                    SqlDataReader dataReaderYearMonth = databaseConnect.GetDataReader(sqlYearMonth);
                    while (dataReaderYearMonth.Read())
                    {
                        ListBoxItem item = new ListBoxItem();
                        item.SetResourceReference(ListBoxItem.StyleProperty, "FinanceRecordItem");
                        item.ApplyTemplate();
                        Label dateLbl = item.Template.FindName("date", item) as Label;
                        Label itemLbl = item.Template.FindName("item", item) as Label;
                        Label countLbl = item.Template.FindName("count", item) as Label;
                        Label moneyLbl = item.Template.FindName("money", item) as Label;

                        dateLbl.Content = dataReaderYearMonth[6].ToString().Trim() + "年 "
                            + dataReaderYearMonth[1].ToString().Trim() + "月 "
                            + dataReaderYearMonth[5].ToString().Trim() + "日 ";

                        itemLbl.Content = dataReaderYearMonth[2].ToString().Trim();

                        countLbl.Content = dataReaderYearMonth[3].ToString().Trim() + " × " + dataReaderYearMonth[4].ToString().Trim();
                        moneyLbl.Content = ((int)dataReaderYearMonth[3] * (double)dataReaderYearMonth[4]).ToString();

                        financeListBox.Items.Add(item);
                    }
                    dataReaderYearMonth.Close();

                    for (int i = 0; i < 12; i++)
                    {
                        month++;
                        if (month > 12)
                        {
                            month = 1;
                            year++;
                        }
                        string sqlEmpty = "select * from FinanceTable where year = " + year.ToString()
                                        + " and month = " + month.ToString()
                                        + " and branch_name = '" + branchName + "'";
                        SqlDataReader dataReaderEmpty = databaseConnect.GetDataReader(sqlEmpty);
                        if (dataReaderEmpty.Read())
                        {
                            ListBoxItem lbi = new ListBoxItem();
                            lbi.SetResourceReference(ListBoxItem.StyleProperty, "ListBoxItemStyle1");
                            lbi.Content = year.ToString() + "-" + month.ToString();
                            CaiwuListBox.Items.Add(lbi);
                        }
                        dataReaderEmpty.Close();

                    }
                }
                else
                {
                    dataReaderMonth.Close();
                }

            }
            else
            {
                dataReaderYear.Close();
            }

            if (CaiwuListBox.Items.Count > 0)
                (CaiwuListBox.Items[CaiwuListBox.Items.Count - 1] as ListBoxItem).IsSelected = true;

        }

        private void financeGraph(int year, int month)
        {
            finGraph.ApplyTemplate();
            for (int i = 1; i < 32; i++)
            {
                Rectangle rec = finGraph.Template.FindName("r" + i.ToString().ToString(), finGraph) as Rectangle;
                Rectangle mRec = finGraph.Template.FindName("mr" + i.ToString().ToString(), finGraph) as Rectangle;
                rec.Visibility = Visibility.Hidden;
                mRec.Visibility = Visibility.Hidden;
            }

            string branchName = getBranchName();
            string sql = "select sum(price), day from FinanceTable where year = " + year
                       + " and month = " + month
                       + " and branch_name = '" + branchName
                       + "' group by day";
            SqlDataReader dataReader = databaseConnect.GetDataReader(sql);
            while (dataReader.Read())
            {
                if (dataReader[0].ToString() == "")
                {
                    dataReader.Close();
                    return;
                }
                if ((double)dataReader[0] > 0)
                {
                    Rectangle rec = finGraph.Template.FindName("r" + dataReader[1].ToString(), finGraph) as Rectangle;
                    rec.Height = (double)dataReader[0] / 10;
                    rec.Visibility = Visibility.Visible;
                }
                else if ((double)dataReader[0] < 0)
                {
                    Rectangle rec = finGraph.Template.FindName("mr" + dataReader[1].ToString(), finGraph) as Rectangle;
                    rec.Height = -(double)dataReader[0] / 10;
                    rec.Visibility = Visibility.Visible;

                }

            }
            dataReader.Close();
        }

        private void CaiwuListBox_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            if (CaiwuListBox.SelectedItem != null)
            {
                loadMonthSelected();
            }
        }

        private void financeAdd_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            //if (itemName.Text == "") return;
            if (!finItemRegex.IsMatch(itemName.Text))
            {
                MessageBox.Show("项目名输入错误！");
                itemName.Clear();
                return;
            }
            if (!finNumRegex.IsMatch(number.Text))
            {
                MessageBox.Show("数量输入错误或输入太大！");
                number.Clear();
                return;
            }
            if (!finPriceRegex.IsMatch(price.Text))
            {
                MessageBox.Show("价格输入错误或输入太大！");
                price.Clear();
                return;
            }
            updateFinance();
        }

        private int GetWeek(DateTime now)
        {
            int weekOfYear = gc.GetWeekOfYear(now, System.Globalization.CalendarWeekRule.FirstDay, DayOfWeek.Sunday);
            return weekOfYear;
        }

        private int GetMonth(DateTime now)
        {
            int monthOfYear = gc.GetMonth(now);
            return monthOfYear;
        }

        private int GetDay(DateTime now)
        {
            int dayOfMonth = gc.GetDayOfMonth(now);
            return dayOfMonth;
        }

        private int GetYear(DateTime now)
        {
            int year = gc.GetYear(now);
            return year;
        }
        GregorianCalendar gc = new System.Globalization.GregorianCalendar();
    }
}
